package tech.mhuang.pacebox.oss.interceptor;

import tech.mhuang.pacebox.core.chain.BaseChain;
import tech.mhuang.pacebox.core.chain.BaseInterceptor;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.oss.BaseOssHandler;
import tech.mhuang.pacebox.oss.domain.OssDownloadRequest;
import tech.mhuang.pacebox.oss.domain.OssDownloadResult;

import java.util.Map;

/**
 * oss下载接口拦截
 *
 * @author mhuang
 * @since 1.0.0
 */
public interface OssDownloadInterceptor extends BaseInterceptor<BaseChain<OssDownloadRequest, OssDownloadResult>, OssDownloadResult> {

    class Standard implements OssDownloadInterceptor {

        private final Map<String, BaseOssHandler> ossHandlerMap;

        public Standard(Map<String, BaseOssHandler> ossHandlerMap) {
            this.ossHandlerMap = ossHandlerMap;
        }

        @Override
        public OssDownloadResult interceptor(BaseChain<OssDownloadRequest, OssDownloadResult> chain) {
            OssDownloadRequest request = chain.request();
            OssDownloadResult result;
            BaseOssHandler ossHandler = ossHandlerMap.get(request.getType());
            if (ObjectUtil.isEmpty(ossHandler)) {
                result = OssDownloadResult.builder().success(false)
                        .message("找不到下载的OSS配置")
                        .throwable(new BusinessException(500, "找不到下载的OSS配置")).build();
            } else {
                result = ossHandler.download(request);
            }
            return result;
        }
    }
}